package com.qm.console.service.anchor.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.ImmutableMap;
import com.qm.console.component.exception.BusinessException;
import com.qm.console.component.util.DateUtil;
import com.qm.console.component.util.HttpInvokeUtil;
import com.qm.console.component.util.TimeUtils;
import com.qm.console.controller.dto.BaseDO;
import com.qm.console.controller.dto.BaseRsp;
import com.qm.console.controller.dto.ResultEnum;

import com.qm.console.controller.vo.comm.UserInfoVO;
import com.qm.console.dao.mapper.*;
import com.qm.console.dao.model.*;

import com.qm.console.pubdef.constant.UrlConstant;
import com.qm.console.pubdef.dto.analysis.AnchorAnalysisDTO;
import com.qm.console.pubdef.dto.anchor.*;
import com.qm.console.pubdef.dto.user.PageInfoDTO;
import com.qm.console.service.analysis.AnalysisService;
import com.qm.console.service.anchor.AnchorService;
import com.qm.console.utils.AliVodUtils;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.HttpPut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import lombok.extern.slf4j.Slf4j;

import static com.qm.console.utils.EmojiConverterUtil.emojiRecovery;

@Service
@Slf4j
public class AnchorServiceImpl implements AnchorService {
    private final String anchorAdminUrl="/check";

    @Autowired
    private AnchorAnalysisDOMapper anchorAnalysisDOMapper;

    @Override
    public BaseDO<PageInfoDTO<LiveVerificationDOWithBLOBs>> listAnchorVerifyAdmin(Map<String, String> paramMap) {
        String url= UrlConstant.ApiServerHost+anchorAdminUrl+"/live/list";
        String body= HttpInvokeUtil.httpGet(url,paramMap, null);
        BaseDO<PageInfoDTO<LiveVerificationDOWithBLOBs>> rsp=JSONObject.parseObject(body,BaseDO.class);
        Object rspData=rsp.getData();
        final JSONObject data=(JSONObject) rspData;
        JSONArray recordIds = new JSONArray();
        if(data.containsKey("list")){
            JSONArray list= data.getJSONArray("list");

            for(int i=0;i<list.size();i++){
                JSONObject item=list.getJSONObject(i);
                String withDrawId=item.getString("recordId");
                if(withDrawId!=null){
                    recordIds.add(withDrawId);
                }
            }
            String records = StringUtils.join(recordIds, ",");
            Map<String, Object> queryMap = structureQueryMap(paramMap);
            queryMap.put("recordIds", records);
            queryMap.put("status", 0);
            log.info(records);
            List<LiveVerificationDOWithBLOBs> liveList = liveVerificationDOMapper.list(queryMap);

            Map<String, Object> recordMap = new HashMap<>();
            for (LiveVerificationDOWithBLOBs liveVerificationDOWithBLOBs : liveList) {
                recordMap.put(liveVerificationDOWithBLOBs.getRecordId(), liveVerificationDOWithBLOBs.getAutoLive());
            }

            for(int i=0;i<list.size();i++){
                JSONObject item=list.getJSONObject(i);
                String withDrawId=item.getString("recordId");
                if(withDrawId!=null){
                    item.put("recordId",withDrawId);
                    item.put("autoLive", recordMap.getOrDefault(withDrawId, 0));
                }
            }
        }
        return rsp;
    }

    @Override
    public BaseRsp updateAnchorVerifyAdmin(AnchorVerifyAdminDTO updateDTO){
        String recordId=updateDTO.getRecord().getRecordId();
        Integer status=updateDTO.getStatus();
        String reason=updateDTO.getReason();
        String url=UrlConstant.ApiServerHost+anchorAdminUrl+"/certification";

        Map<String, Object> updateMap = new HashMap<>();
        updateMap.put("recordId", recordId);
        updateMap.put("status", status);
        updateMap.put("reason", reason);
        String req = JSONObject.toJSONString(updateMap);
        String body = HttpInvokeUtil.httpPostJson(url, req, UrlConstant.DefaultEncode, null);
        BaseRsp rsp=JSONObject.parseObject(body,BaseRsp.class);
        return rsp;
    }

    @Override
    public BaseRsp getAnchorStatistic(AnchorAnalysisDTO queryDTO){
        return new BaseRsp(ResultEnum.SUCCESS, ImmutableMap.of("count", anchorAnalysisDOMapper.count(queryDTO),
                "list", anchorAnalysisDOMapper.list(queryDTO)));
    }

    @Override
    public BaseDO<PageInfoDTO<AvatarAuditDO>> listAnchorAvatarAdmin(Map<String, String> paramMap) {
        String url= UrlConstant.ApiServerHost+anchorAdminUrl+"/avatar/list";
        String body= HttpInvokeUtil.httpGet(url,paramMap, null);
        BaseDO<PageInfoDTO<AvatarAuditDO>> rsp=JSONObject.parseObject(body,BaseDO.class);
        return rsp;
    }

    @Override
    public BaseRsp updateAnchorAvatarAdmin(AnchorVerifyAvatarAdminDTO updateDTO){
        String url=UrlConstant.ApiServerHost+anchorAdminUrl+"/avatar";
        Map<String, Object> updateMap = new HashMap<>();
        List<Integer> userIds = new ArrayList();
        updateDTO.getRecords().forEach(item->{
            userIds.add(item.getUserId());
        });
        updateMap.put("status", updateDTO.getStatus());
        updateMap.put("userIds", userIds);

        String req = JSONObject.toJSONString(updateMap);
        String body = HttpInvokeUtil.httpPostJson(url, req, UrlConstant.DefaultEncode, null);
        BaseRsp rsp=JSONObject.parseObject(body,BaseRsp.class);
        return rsp;
    }

    @Override
    public BaseDO listAnchorPhotoVerifyAdmin(Map<String, String> paramMap) {
        String url= UrlConstant.ApiServerHost+anchorAdminUrl+"/photos/list";
        String body= HttpInvokeUtil.httpGet(url,paramMap, null);
        BaseDO rsp=JSONObject.parseObject(body,BaseDO.class);
        return rsp;
    }

    @Override
    public BaseRsp updateAnchorPhotoVerifyAdmin(AnchorVerifyPhotoAdminDTO updateDTO){
        String url= UrlConstant.ApiServerHost+anchorAdminUrl+"/photos";

        JSONObject reqJson = (JSONObject) JSONObject.toJSON(updateDTO);
        JSONArray list = reqJson.getJSONArray("userPhotosList");
        for (int i=0; i<list.size(); i++){
            JSONObject item = list.getJSONObject(i);
            Integer userId = item.getJSONObject("userInfoVo").getInteger("userId");
            item.put("status", Integer.parseInt(item.get("status").toString()));
            item.put("userId", userId);
            item.remove("userInfoVo");
            JSONArray photos = item.getJSONArray("photos");
            JSONArray urls = new JSONArray();
            for (int j=0; j<photos.size(); j++){
               urls.add(photos.getJSONObject(j).getString("photo"));
            }
            item.put("photos", urls);
        }

        String req = JSONObject.toJSONString(reqJson);
        String body = HttpInvokeUtil.httpPostJson(url, req, UrlConstant.DefaultEncode, null);
        BaseRsp rsp=JSONObject.parseObject(body,BaseRsp.class);
        return rsp;
    }

    @Override
    public BaseDO listAnchorVideoVerifyAdmin(Map<String, String> paramMap) {
        String url= UrlConstant.ApiServerHost+anchorAdminUrl+"/video/list";
        String body= HttpInvokeUtil.httpGet(url,paramMap, null);
        BaseDO rsp=JSONObject.parseObject(body, BaseDO.class);
        return rsp;
    }

    @Override
    public  BaseRsp updateAnchorVideoVerifyAdmin(AnchorVerifyVideoAdminDTO updateDTO){
        String url=UrlConstant.ApiServerHost+anchorAdminUrl+"/video";
        JSONObject reqBody = new JSONObject();
        List<VideoAuditDO> records = updateDTO.getRecords();
        List<Integer> userIds = new ArrayList<>();
        records.forEach(item->{
            userIds.add(item.getUserId());
        });
        reqBody.put("status", updateDTO.getStatus());
        reqBody.put("userIds", userIds);

        String req=JSONObject.toJSONString(reqBody);
        String body=HttpInvokeUtil.httpPostJson(url,req,UrlConstant.DefaultEncode,null);
        BaseRsp rsp=JSONObject.parseObject(body,BaseRsp.class);
        return rsp; 
    }


    @Override
    public BaseDO listAnchorCoverImageAdmin(Map<String, String> paramMap) {
        String url= UrlConstant.ApiServerHost+anchorAdminUrl+"/background/image/list";
        String body= HttpInvokeUtil.httpGet(url,paramMap, null);
        BaseDO rsp=JSONObject.parseObject(body,BaseDO.class);
        return rsp;
    }

    @Override
    public BaseRsp updateAnchorCoverVerifyAdmin(AnchorVerifyCoverImageDTO updateDTO){
        String url= UrlConstant.ApiServerHost+anchorAdminUrl+"/background/image";
        JSONObject reqBody = new JSONObject();

        List<BackgroundAuditDO> records = updateDTO.getRecords();
        List<Integer> userIds = new ArrayList<>();
        records.forEach(item->{
            userIds.add(item.getUserId());
        });
        reqBody.put("status", updateDTO.getStatus());
        reqBody.put("userIds", userIds);

        String req = JSONObject.toJSONString(reqBody);
        String body = HttpInvokeUtil.httpPostJson(url, req, UrlConstant.DefaultEncode, null);
        BaseRsp rsp=JSONObject.parseObject(body,BaseRsp.class);
        return rsp;
    }

    @Autowired
    private ScreenShotsDOMapper screenShotsDOMapper;
    @Autowired
    private VideoRecordDOMapper videoRecordDOMapper;

    @Override
    public List<ScreenShotsDO> listVideoThumbAll(ScreenShotQueryDTO queryDTO) {
        generateTableId(queryDTO);
        return screenShotsDOMapper.list(queryDTO);
    }

    @Override
    public int countVideoThumbAll(ScreenShotQueryDTO queryDTO) {
        generateTableId(queryDTO);
        return screenShotsDOMapper.count(queryDTO);
    }

    private void generateTableId(ScreenShotQueryDTO queryDTO) {
        String channel = queryDTO.getChannelId();
        String tableId = channel.substring(channel.length() - 1, channel.length());
        queryDTO.setTableId(tableId);
    }

    @Override
    public List<Integer> listVideoThumbUser(ScreenShotQueryDTO queryDTO) {
        generateTableId(queryDTO);
        return screenShotsDOMapper.listUid(queryDTO);
    }

    @Override
    public List<VideoRecordDO> listVideoThumb(VideoRecordQueryDTO queryDTO) {
        return videoRecordDOMapper.list(queryDTO);
    }

    @Override
    public int countVideoThumb(VideoRecordQueryDTO queryDTO) {
        return videoRecordDOMapper.count(queryDTO);
    }

    @Override
    public void deleteVideoThumb(String channelId) {
        String tableId = channelId.substring(channelId.length() - 1, channelId.length());
        screenShotsDOMapper.markDelete(tableId, channelId);
        videoRecordDOMapper.removeImage(channelId);
    }

    @Override
    public void verifyChat(List<String> chatIds) {
        videoRecordDOMapper.verifyChat(chatIds);
    }

    @Override
    public void verifyUserChat(String userId) {
        videoRecordDOMapper.verifyUserChat(userId);
    }

    private static final String[] SCREEN_SHOT_SUBFIX = new String[] {
            "0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"
    };

    @Autowired
    private AliVodUtils aliVodUtils;

    @Override
    public void removeDeletedVideoThumb() {
        for (String i : SCREEN_SHOT_SUBFIX) {
            removeDeletedVideoThumb(i);
        }
    }

    private void removeDeletedVideoThumb(String table) {
        final List<ScreenShotsDO> items = screenShotsDOMapper.listDeleteImages(table);
        log.info("delete {} items from table: screen_shots_{}", items.size(), table);
        items.forEach(item -> {
            if (aliVodUtils.deleteImage(item.getUrl())) {
                screenShotsDOMapper.deleteItem(table, item.getId());
            }
        });
    }

    //------------- immsg ---------------//

    @Autowired
    private ImMsgDOMapper imMsgDOMapper;
    @Autowired
    private DateUtil dateUtil;

    @Override
    public BaseRsp listIMMsgs(ImMsgQueryDTO query) {
//        return imMsgDOMapper.list();
        if (query.getOffset() == null || query.getLimit() == null) {
            throw new BusinessException(ResultEnum.PARA_ERR);
        }
        if (!StringUtils.isEmpty(query.getContent())) {
            query.setContent(String.format("%%%s%%", query.getContent()));
            query.setContent(query.getContent().replaceAll("\\s+", "%"));
        }
        if (!StringUtils.isEmpty(query.getMsgType())) {
            String[] types = query.getMsgType().split(",");
            query.setMsgTypes(Arrays.stream(types).map(Integer::parseInt).collect(Collectors.toList()));
        }
        Date startTime;
        Date endTime;
        Date minTime = new Date(2020 - 1900, Calendar.JULY, 1);
        Date maxTime = new Date();
        if (query.getStartTime() == null) {
            startTime = minTime;
        } else {
            startTime = TimeUtils.parse(query.getStartTime(), TimeUtils.DATE_FORMAT_DATE_D);
            if (startTime.getTime() < minTime.getTime()) {
                startTime = minTime;
            }
        }
        if (query.getEndTime() == null) {
            endTime = maxTime;
        } else {
            endTime = TimeUtils.parse(query.getEndTime(), TimeUtils.DATE_FORMAT_DATE_D);
            if (endTime.getTime() > maxTime.getTime()) {
                endTime = maxTime;
            }
        }
        Calendar startTimeC = Calendar.getInstance();
        startTimeC.setTime(startTime);
        Calendar endTimeC = Calendar.getInstance();
        endTimeC.setTime(endTime);
        List<String> months = dateUtil.listMonths(startTimeC, endTimeC);

        List<String> tables = months.stream().map(month -> "immsg_" + month).collect(Collectors.toList());
        query.setTables(tables);
        if (tables.isEmpty()) {
            return new BaseRsp(ResultEnum.SUCCESS, ImmutableMap.of("list", Collections.emptyList(), "count", 0));
        }
        List<TableCountDO> counts = imMsgDOMapper.count(query);
        Collections.reverse(counts);

        final List<String> contentTables = new ArrayList<>();
        int totalCount = 0;
        int realOffset = 0;
        boolean started = false;
        for (TableCountDO count : counts) {
            if (query.getOffset() >= totalCount && query.getOffset() < totalCount + count.getTotal()) {
                //临界条件..
                contentTables.add(count.getTableName());
                realOffset = query.getOffset() - totalCount;
                started = true;
            } else if (started && query.getOffset() + query.getLimit() >= totalCount) {
                contentTables.add(count.getTableName());
            }
            totalCount += count.getTotal();
        }
        if (contentTables.isEmpty()) {
            return new BaseRsp(ResultEnum.SUCCESS, ImmutableMap.of("list", Collections.emptyList(), "count", 0));
        }
        query.setOffset(realOffset);
        query.setTables(contentTables);
        List<ImMsgDO> list = imMsgDOMapper.list(query);
        for(ImMsgDO msg: list){
            if(msg.getMsgType() == 4){
                msg.setContent(aliVodUtils.getMediaUrl(msg.getContent(), "mp3"));
            }
        }

        return new BaseRsp(ResultEnum.SUCCESS, ImmutableMap.of("list", list, "count", totalCount));
    }

    @Override
    public BaseRsp sessionMsg(ImMsgQueryDTO query){
        if (query.getOffset() == null || query.getLimit() == null) {
            throw new BusinessException(ResultEnum.PARA_ERR);
        }
        if (!StringUtils.isEmpty(query.getContent())) {
            query.setContent(String.format("%%%s%%", query.getContent()));
            query.setContent(query.getContent().replaceAll("\\s+", "%"));
        }
        if (!StringUtils.isEmpty(query.getMsgType())) {
            String[] types = query.getMsgType().split(",");
            query.setMsgTypes(Arrays.stream(types).map(Integer::parseInt).collect(Collectors.toList()));
        }

        Date startTime;
        Date endTime;
        Date minTime = new Date(2020 - 1900, Calendar.JULY, 1);
        Date maxTime = new Date();
        if (query.getStartTime() == null) {
            startTime = minTime;
        } else {
            startTime = TimeUtils.parse(query.getStartTime(), TimeUtils.DATE_FORMAT_DATE_D);
            if (startTime.getTime() < minTime.getTime()) {
                startTime = minTime;
            }
        }
        if (query.getEndTime() == null) {
            endTime = maxTime;
        } else {
            endTime = TimeUtils.parse(query.getEndTime(), TimeUtils.DATE_FORMAT_DATE_D);
            if (endTime.getTime() > maxTime.getTime()) {
                endTime = maxTime;
            }
        }
        Calendar startTimeC = Calendar.getInstance();
        startTimeC.setTime(startTime);
        Calendar endTimeC = Calendar.getInstance();
        endTimeC.setTime(endTime);
        List<String> months = dateUtil.listMonths(startTimeC, endTimeC);

        List<String> tables = months.stream().map(month -> "immsg_" + month).collect(Collectors.toList());
        if (tables.isEmpty()) {
            return new BaseRsp(ResultEnum.SUCCESS, ImmutableMap.of("list", Collections.emptyList(), "count", 0));
        }
        query.setTables(tables);

        Integer totalCount = imMsgDOMapper.sessionCount(query);
        List<ImMsgDO> list = imMsgDOMapper.sessionList(query);
        for(ImMsgDO msg: list){
            if(msg.getMsgType() == 4){
                msg.setContent(aliVodUtils.getMediaUrl(msg.getContent(), "mp3"));
            }
        }
        return new BaseRsp(ResultEnum.SUCCESS, ImmutableMap.of("list", list, "count", totalCount));
    }

    @Override
    public BaseRsp reversionRate(ImMsgQueryDTO query) {
        if (query.getOffset() == null || query.getLimit() == null) {
            throw new BusinessException(ResultEnum.PARA_ERR);
        }
        if (!StringUtils.isEmpty(query.getContent())) {
            query.setContent(String.format("%%%s%%", query.getContent()));
            query.setContent(query.getContent().replaceAll("\\s+", "%"));
        }
        if (!StringUtils.isEmpty(query.getMsgType())) {
            String[] types = query.getMsgType().split(",");
            query.setMsgTypes(Arrays.stream(types).map(Integer::parseInt).collect(Collectors.toList()));
        }
        Date startTime;
        Date endTime;
        Date minTime = new Date(2020 - 1900, Calendar.JULY, 1);
        Date maxTime = new Date();
        if (query.getStartTime() == null) {
            startTime = minTime;
        } else {
            startTime = TimeUtils.parse(query.getStartTime(), TimeUtils.DATE_FORMAT_DATE_D);
            if (startTime.getTime() < minTime.getTime()) {
                startTime = minTime;
            }
        }
        if (query.getEndTime() == null) {
            endTime = maxTime;
        } else {
            endTime = TimeUtils.parse(query.getEndTime(), TimeUtils.DATE_FORMAT_DATE_D);
            if (endTime.getTime() > maxTime.getTime()) {
                endTime = maxTime;
            }
        }
        Calendar startTimeC = Calendar.getInstance();
        startTimeC.setTime(startTime);
        Calendar endTimeC = Calendar.getInstance();
        endTimeC.setTime(endTime);
        List<String> months = dateUtil.listMonths(startTimeC, endTimeC);

        List<String> tables = months.stream().map(month -> "immsg_" + month).collect(Collectors.toList());
        query.setTables(tables);
        if (tables.isEmpty()) {
            return new BaseRsp(ResultEnum.SUCCESS, ImmutableMap.of("list", Collections.emptyList(), "count", 0));
        }
        List<TableCountDO> counts = imMsgDOMapper.reversionRateCount(query);

        Collections.reverse(counts);

        final List<String> contentTables = new ArrayList<>();
        int totalCount = 0;
        int realOffset = 0;
        boolean started = false;
        for (TableCountDO count : counts) {
            if (query.getOffset() >= totalCount && query.getOffset() < totalCount + count.getTotal()) {
                //临界条件..
                contentTables.add(count.getTableName());
                realOffset = query.getOffset() - totalCount;
                started = true;
            } else if (started && query.getOffset() + query.getLimit() >= totalCount) {
                contentTables.add(count.getTableName());
            }
            totalCount += count.getTotal();
        }
        if (contentTables.isEmpty()) {
            return new BaseRsp(ResultEnum.SUCCESS, ImmutableMap.of("list", Collections.emptyList(), "count", 0));
        }
        query.setOffset(realOffset);
        query.setTables(contentTables);
        List<ImMsgDO> list = imMsgDOMapper.reversionRateList(query);
        for(ImMsgDO msg: list){
            if(msg.getMsgType() == 4){
                msg.setContent(aliVodUtils.getMediaUrl(msg.getContent(), "mp3"));
            }
        }

        return new BaseRsp(ResultEnum.SUCCESS, ImmutableMap.of("list", list, "count", totalCount));
    }

    @Override
    public void verifyIMMsg(ImMsgUpdateDTO query) {
        calImMsgTable(query);
        imMsgDOMapper.verify(query);
    }

    @Override
    public void deleteIMMsg(ImMsgUpdateDTO query) {
        calImMsgTable(query);
        imMsgDOMapper.delete(query);
    }

    private void calImMsgTable(ImMsgUpdateDTO query) {
        String time = query.getTime();
        Date dateTime = TimeUtils.parse(time, TimeUtils.DATE_FORMAT_DATE_S);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(dateTime);
        String format = calendar.get(Calendar.MONTH) > 8 ? "immsg_%s_%s" : "immsg_%s_0%s";
        String table = String.format(format, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1);
        query.setTable(table);
    }


    //------------- Anchor Audit ---------------//

    @Autowired
    private LiveVerificationDOMapper liveVerificationDOMapper;

    @Override
    public void saveLiveAuditRecord(LiveVerificationDOWithBLOBs record){
        // 保存真人认证已审核数据记录
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("userId", record.getUserId());
        queryMap.put("applyTime", record.getApplyTime());
        Integer isExist = liveVerificationDOMapper.isExist(queryMap);
        if (isExist == 0 ){
            if (new HashSet<Integer>(){{add(1); add(2);}}.contains(record.getStatus()))
            liveVerificationDOMapper.insertSelective(record);
        }
        else{
            liveVerificationDOMapper.updateTime(queryMap);
        }
        System.out.println(MessageFormat.format("[ saveLiveAuditRecord ]： {0}", record.toString()));
    }

    @Autowired
    private SysTaskSchedulingDOMapper sysTaskSchedulingDOMapper;

    @Override
    public BaseRsp saveDynamicState(DynamicStateDTO updateDTO){
        String args = JSONObject.toJSONString(updateDTO);
        String runTime = updateDTO.getRunTime();
        if (runTime != null){
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("args", args);
            paramMap.put("name", "MODIFY_DYNAMIC_STATE");
            paramMap.put("status", "1");
            paramMap.put("run_time", updateDTO.getRunTime());
            sysTaskSchedulingDOMapper.insertTake(paramMap);
        }else {
            log.info("没有时间参数立即执行");
            String url= UrlConstant.ApiServerHost+"/check/update_official_switch";
            HttpInvokeUtil.httpPostJson(url, args, UrlConstant.DefaultEncode, null);
        }
        return new BaseRsp(ResultEnum.SUCCESS, ImmutableMap.of("message", "ok"));
    }

    @Override
    public BaseDO<PageInfoDTO<LiveVerificationDOWithBLOBs>> listLiveAuditRecord(Map<String, String> paramMap){
        Map<String, Object> queryMap = structureQueryMap(paramMap);
        queryMap.put("status", paramMap.get("status"));

        // 获取已审核数据列表
        List<LiveVerificationDOWithBLOBs> list = liveVerificationDOMapper.list(queryMap);
        for (int i=0; i<list.size(); i++){
            LiveVerificationDOWithBLOBs item = list.get(i);
            String nickName = item.getNickname();
            item.setNickname(emojiRecovery(nickName));
            item.setGoddessStatus(item.getStatus());
        }

        // 获取当前获取数据总数
        Integer count = list.size();
        System.out.println(MessageFormat.format("[ listLiveAuditRecord ]： total:{0}; content:{1}", count.toString(), list.toString()));
        // 获取所有数据总数
        Integer total = liveVerificationDOMapper.total(queryMap);

        Integer page = Integer.parseInt(paramMap.getOrDefault("pageNum", "1"));
        Integer limit = Integer.parseInt(paramMap.getOrDefault("pageSize", "100"));

        PageInfoDTO pageInfo = structurePageInfo(list, total, count, page, limit);


        return new BaseDO(pageInfo);
    }


    @Autowired
    private AvatarAuditDOMapper avatarAuditDOMapper;

    @Override
    public void saveAvatarAuditRecord(List<AvatarAuditDO> records){
        //避免重复内容审核插入数据库
        System.out.println(MessageFormat.format("[ saveAvatarAuditRecord ]： {0}", records.toString()));
        for (int i=0; i<records.size(); i++){
            AvatarAuditDO record = records.get(i);
            Map<String, Object> queryMap = new HashMap<>();
            queryMap.put("userId", record.getUserId());
            queryMap.put("applyTime", record.getApplyTime());
            Integer isExist = avatarAuditDOMapper.isExist(queryMap);
            if (isExist != 0 ) {
                avatarAuditDOMapper.updateTime(queryMap);
                records.remove(i);
                i--;
            }
        };
        if (records.size()>0){
            avatarAuditDOMapper.insertMultiTerm(records);
        }
    }

    @Override
    public BaseDO<PageInfoDTO<AvatarAuditInfoDTO>> listAvatarAuditRecord(Map<String, String> paramMap){
        Map<String, Object> queryMap = structureQueryMap(paramMap);
        if (paramMap.containsKey("gender") && paramMap.get("gender")!=null && paramMap.get("gender")!=""){
            queryMap.put("gender", Integer.valueOf(paramMap.get("gender")));
        }
        if (paramMap.containsKey("identifyType") && paramMap.get("identifyType")!=null && paramMap.get("identifyType")!=""){
            queryMap.put("identifyType", Integer.valueOf(paramMap.get("identifyType")));
        }

        // 获取已审核数据列表
        List<AvatarAuditDO> queryList = avatarAuditDOMapper.list(queryMap);
        for (int i=0; i<queryList.size(); i++){
            AvatarAuditDO item = queryList.get(i);
            String nickName = item.getNickname();
            item.setNickname(emojiRecovery(nickName));
        }

        // 数据格式化
        List<AvatarAuditInfoDTO> list = new ArrayList<>();
        queryList.forEach(item->{
            AvatarAuditInfoDTO tmp = new AvatarAuditInfoDTO();
            UserInfoVO userInfo = new UserInfoVO();
            tmp.setAvatar(item.getAvatar());
            tmp.setApplyTime(item.getApplyTime());
            tmp.setIdentifyType(item.getIdentifyType());
            tmp.setStatus(item.getStatus());
            userInfo.setUserId(item.getUserId());
            userInfo.setNickname(item.getNickname());
            userInfo.setGender(item.getGender());
            userInfo.setMValue(item.getmValue());
            userInfo.setRichValue(item.getRichValue());
            userInfo.setCoinsNum(item.getCoinsNum());
            userInfo.setDiamondsNum(item.getDiamondsNum());
            userInfo.setForbidState(item.getForbidState());
            tmp.setUserInfoVo(userInfo);
            list.add(tmp);
        });
        // 获取当前获取数据总数
        Integer count = list.size();
        System.out.println(MessageFormat.format("[ listAvatarAuditRecord ]： total:{0}; content:{1}", count.toString(), list.toString()));

        // 获取所有数据总数
        Integer total = avatarAuditDOMapper.total(queryMap);

        Integer page = Integer.parseInt(paramMap.getOrDefault("pageNum", "1"));
        Integer limit = Integer.parseInt(paramMap.getOrDefault("pageSize", "100"));

        PageInfoDTO pageInfo = structurePageInfo(list, total, count, page, limit);

        return new BaseDO(pageInfo);
    }


    @Autowired
    private PhotosAuditRecordsMapper photosAuditRecordsMapper;
    @Autowired
    private AuditPhotosMapper auditPhotosMapper;

    public void saveAuditRecord(JSONArray list){
        System.out.println(MessageFormat.format("[ saveAuditRecord ]： {0}", list.toString()));
        //避免重复内容审核插入数据库
        for (int i=0; i<list.size(); i++){
            JSONObject record = (JSONObject) JSONObject.toJSON(list.get(i));
            JSONArray photos = record.getJSONArray("photos");
            for (int j=0; j<photos.size(); j++){
                JSONObject photo = photos.getJSONObject(j);
                Map<String, Object> queryMap = new HashMap<>();
                JSONObject userInfoVo = record.getJSONObject("userInfoVo");
                queryMap.put("userId", userInfoVo.get("userId"));
                queryMap.put("applyTime", record.get("applyTime"));
                queryMap.put("photo", photo.getString("photo"));
                Integer isExist = auditPhotosMapper.isExist(queryMap);
                if (isExist != 0 ) {
                    auditPhotosMapper.updateTime(queryMap);
                    photosAuditRecordsMapper.updateTime(queryMap);
                    photos.remove(i);
                    j--;
                }
            }
            if (photos.size()==0){
                list.remove(i);
                i--;
            }
        };
        if (list.size()>0) {
            photosAuditRecordsMapper.insertMultiTerm(list);
            auditPhotosMapper.insertMultiTerm(list);
        }
    }


    public BaseDO listPhotosAuditRecord(Map<String, String> paramMap){
        Map<String, Object> queryMap = structureQueryMap(paramMap);

        // 获取已审核记录列表
        List<JSONObject> queryList = photosAuditRecordsMapper.list(queryMap);

        Map<String, JSONObject> tmpMap = new HashMap<>();

        // 数据格式化
        for (int i=0; i<queryList.size(); i++){

            JSONObject item = queryList.get(i);

            String judgeKey = item.getLong("apply_time") + "." + item.getInteger("user_id") + "." + item.getInteger("status");
            if (tmpMap.containsKey(judgeKey)){
                tmpMap.get(judgeKey).getJSONArray("photos").add(item.get("photo"));
            }
            else{
                JSONObject tmp = new JSONObject();
                JSONArray photos = new JSONArray();
                JSONObject userInfoVo = new JSONObject();
                JSONObject photosObject = new JSONObject();

                photosObject.put("photo", item.get("photo"));
                photosObject.put("real", item.get("real"));
                photos.add(photosObject);

                userInfoVo.put("userId", item.get("user_id"));
                userInfoVo.put("nickname", emojiRecovery(item.get("nickname").toString()));
                userInfoVo.put("gender", item.get("gender"));
                userInfoVo.put("mValue", item.get("m_value"));
                userInfoVo.put("richValue", item.get("rich_value"));
                userInfoVo.put("coinsNum", item.get("coins_num"));
                userInfoVo.put("diamondsNum", item.get("diamonds_num"));
                userInfoVo.put("forbidState", item.get("forbid_state"));

                tmp.put("applyTime", item.getLong("apply_time"));
                tmp.put("identifyType", item.getInteger("identifyType"));
                tmp.put("userInfoVo", userInfoVo);
                tmp.put("photos", photos);
                tmp.put("status", item.getInteger("status"));

                tmpMap.put(judgeKey, tmp);
            }
        }
        List<JSONObject> list = new ArrayList<>(tmpMap.values());
        // 获取当前获取数据总数
        Integer count = list.size();
        System.out.println(MessageFormat.format("[ listPhotosAuditRecord ]： total:{0}; content:{1}", count.toString(), list.toString()));

        // 获取所有数据总数
        Integer total = photosAuditRecordsMapper.total(queryMap);
        Integer page = Integer.parseInt(paramMap.getOrDefault("pageNum", "1"));
        Integer limit = Integer.parseInt(paramMap.getOrDefault("pageSize", "100"));
        PageInfoDTO pageInfo = structurePageInfo(list, total, count, page, limit);

        return new BaseDO(pageInfo);
    }


    @Autowired
    private VideoAuditDOMapper videoAuditDOMapper;

    public void saveVideoAuditRecord(List<VideoAuditDO> records){
        //避免重复内容审核插入数据库
        System.out.println(MessageFormat.format("[ saveVideoAuditRecord ]： {0}", records.toString()));

        for (int i=0; i<records.size(); i++){
            VideoAuditDO record = records.get(i);
            Map<String, Object> queryMap = new HashMap<>();
            queryMap.put("userId", record.getUserId());
            queryMap.put("applyTime", record.getApplyTime());
            Integer isExist = videoAuditDOMapper.isExist(queryMap);
            if (isExist != 0 ) {
                videoAuditDOMapper.updateTime(queryMap);
                records.remove(i);
                i--;
            }
        };
        if (records.size()>0) {
            videoAuditDOMapper.insertMultiTerm(records);
        }
    }

    public BaseDO listVideoAuditRecord(Map<String, String> paramMap){
        Map<String, Object> queryMap = structureQueryMap(paramMap);

        // 获取已审核记录列表
        List<VideoAuditDO> queryList = videoAuditDOMapper.list(queryMap);
        // 数据格式化
        List<JSONObject> list = new ArrayList<>();
        queryList.forEach(item->{
            JSONObject tmp = new JSONObject();
            UserInfoVO userInfo = new UserInfoVO();

            userInfo.setUserId(item.getUserId());
            userInfo.setNickname(emojiRecovery(item.getNickname()));
            userInfo.setGender(item.getGender());
            userInfo.setMValue(item.getmValue());
            userInfo.setRichValue(item.getRichValue());
            userInfo.setCoinsNum(item.getCoinsNum());
            userInfo.setDiamondsNum(item.getDiamondsNum());
            userInfo.setForbidState(item.getForbidState());

            tmp.put("video", item.getVideo());
            tmp.put("status", item.getStatus());
            tmp.put("identifyType", item.getIdentifyType());
            tmp.put("applyTime", item.getApplyTime());
            tmp.put("userInfoVo", userInfo);
            tmp.put("videoStatus", item.getVideoStatus());
            list.add(tmp);
        });
        // 获取当前获取数据总数
        Integer count = list.size();
        System.out.println(MessageFormat.format("[ listVideoAuditRecord ]： total:{0}; content:{1}", count.toString(), list.toString()));
        // 获取所有数据总数
        Integer total = videoAuditDOMapper.total(queryMap);

        Integer page = Integer.parseInt(paramMap.getOrDefault("pageNum", "1"));
        Integer limit = Integer.parseInt(paramMap.getOrDefault("pageSize", "100"));

        PageInfoDTO pageInfo = structurePageInfo(list, total, count, page, limit);

        return new BaseDO(pageInfo);
    }

    @Autowired
    private BackgroundAuditDOMapper backgroundAuditDOMapper;

    public void saveBackgroundAuditRecord(List<BackgroundAuditDO> records){
        //避免重复内容审核插入数据库
        System.out.println(MessageFormat.format("[ saveBackgroundAuditRecord ]： {0}", records.toString()));
        for (int i=0; i<records.size(); i++){
            BackgroundAuditDO record = records.get(i);
            Map<String, Object> queryMap = new HashMap<>();
            queryMap.put("userId", record.getUserId());
            queryMap.put("applyTime", record.getApplyTime());
            Integer isExist = backgroundAuditDOMapper.isExist(queryMap);
            if (isExist != 0 ) {
                backgroundAuditDOMapper.updateTime(queryMap);
                records.remove(i);
                i--;
            }
        };
        if (records.size()>0) {
            backgroundAuditDOMapper.insertMultiTerm(records);
        }
    }

    public BaseDO listBackgroundAuditRecord(Map<String, String> paramMap){
        Map<String, Object> queryMap = structureQueryMap(paramMap);

        // 获取已审核记录列表
        List<BackgroundAuditDO> queryList = backgroundAuditDOMapper.list(queryMap);
        // 数据格式化
        List<JSONObject> list = new ArrayList<>();
        queryList.forEach(item->{
            JSONObject tmp = new JSONObject();
            UserInfoVO userInfo = new UserInfoVO();

            userInfo.setUserId(item.getUserId());
            userInfo.setNickname(emojiRecovery(item.getNickname()));
            userInfo.setGender(item.getGender());
            userInfo.setMValue(item.getmValue());
            userInfo.setRichValue(item.getRichValue());
            userInfo.setCoinsNum(item.getCoinsNum());
            userInfo.setDiamondsNum(item.getDiamondsNum());
            userInfo.setForbidState(item.getForbidState());

            tmp.put("backgroundImage", item.getBackgroundimage());
            tmp.put("applyTime", item.getApplyTime());
            tmp.put("identifyType", item.getIdentifyType());
            tmp.put("userInfoVo", userInfo);
            tmp.put("status", item.getStatus());

            list.add(tmp);
        });
        // 获取当前获取数据总数
        Integer count = list.size();
        System.out.println(MessageFormat.format("[ listBackgroundAuditRecord ]： total:{0}; content:{1}", count.toString(), list.toString()));
        // 获取所有数据总数
        Integer total = backgroundAuditDOMapper.total(queryMap);

        Integer page = Integer.parseInt(paramMap.getOrDefault("pageNum", "1"));
        Integer limit = Integer.parseInt(paramMap.getOrDefault("pageSize", "100"));

        PageInfoDTO pageInfo = structurePageInfo(list, total, count, page, limit);

        return new BaseDO(pageInfo);
    }

    @Override
    public BaseRsp listGoddess(Map<String, String> paramMap){
        String url= UrlConstant.ApiServerHost+anchorAdminUrl+"/gooddess/list";
        String body= HttpInvokeUtil.httpGet(url, paramMap, null);
        BaseRsp rsp=JSONObject.parseObject(body, BaseRsp.class);
        return rsp;
    }

    @Autowired GoddessAuditDOMapper goddessAuditDOMapper;

    @Override
    public BaseRsp listGoddessRecord(Map<String, String> paramMap){
        Map<String, Object> queryMap = structureQueryMap(paramMap);

        // 获取已审核记录列表
        List<GoddessAuditDOWithBLOBs> queryList = goddessAuditDOMapper.list(queryMap);
        for (int i=0; i<queryList.size(); i++){
            GoddessAuditDOWithBLOBs item = queryList.get(i);
            String nickName = item.getNickname();
            item.setNickname(emojiRecovery(nickName));
        }

        // 获取当前获取数据总数
        Integer count = queryList.size();
        System.out.println(MessageFormat.format("[ listGoddessRecord ]： total:{0}; content:{1}", count.toString(), queryList.toString()));
        // 获取所有数据总数
        Integer total = goddessAuditDOMapper.total(queryMap);

        Integer page = Integer.parseInt(paramMap.getOrDefault("pageNum", "1"));
        Integer limit = Integer.parseInt(paramMap.getOrDefault("pageSize", "100"));

        PageInfoDTO pageInfo = structurePageInfo(queryList, total, count, page, limit);

        return new BaseRsp(pageInfo);
    }

    @Override
    public void saveGoddessRecord(GoddessAuditDOWithBLOBs record){
        // 保存真人认证已审核数据记录
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("userId", record.getUserId());
        queryMap.put("applyTime", record.getApplyTime());
        Integer isExist = goddessAuditDOMapper.isExist(queryMap);
        if (isExist == 0 ){
            goddessAuditDOMapper.insertSelective(record);
        }
        else{
            goddessAuditDOMapper.updateTime(queryMap);
        }
        System.out.println(MessageFormat.format("[ saveGoddessRecord ]： {0}", record.toString()));
    }

    @Override
    public BaseRsp updateGoddess(GoddessDTO goddessDTO){
        Long recordId=goddessDTO.getRecord().getRecordId();
        Integer status=goddessDTO.getStatus();
        String url=UrlConstant.ApiServerHost+anchorAdminUrl+"/gooddess/"+recordId+"/"+status;
        HttpPut httpPut=new HttpPut(url);
        String body=HttpInvokeUtil.httpPut(httpPut,UrlConstant.DefaultEncode);
        BaseRsp rsp=JSONObject.parseObject(body,BaseRsp.class);
        return rsp;
    }

    @Autowired CommentAuditDOMapper commentAuditDOMapper;

    @Override
    public BaseRsp listComments(Map<String, String> paramMap){
        String url= UrlConstant.ApiServerHost+anchorAdminUrl+"/comments";
        String body= HttpInvokeUtil.httpGet(url, paramMap, null);

        Map<String, Object> queryMap = structureQueryMap(paramMap);
        if (paramMap.containsKey("postId") && paramMap.get("postId") != null && paramMap.get("postId") != ""){
            queryMap.put("postId", Long.parseLong(paramMap.get("postId")));
        }
        if (paramMap.containsKey("gender") && paramMap.get("gender") != null && paramMap.get("gender") != ""){
            queryMap.put("gender", Integer.valueOf(paramMap.get("gender")));
        }
        if (paramMap.containsKey("status") && paramMap.get("status") != null && paramMap.get("status") != ""){
            queryMap.put("status", Integer.valueOf(paramMap.get("status")));
        }
        Integer limit = Integer.parseInt(queryMap.get("limit").toString()) *  (Integer.parseInt(queryMap.get("offset").toString())+1);
        queryMap.put("limit", limit);
        Set<String> commentIds = commentAuditDOMapper.listCommentId(queryMap);
//        Integer nums = commentIds.size();

        JSONObject jsonRes = JSONObject.parseObject(body);
        JSONObject data = (JSONObject) jsonRes.get("data");
//        data.put("total", data.getInteger("total") - nums);
        JSONArray list = (JSONArray) data.get("list");
        for (int i = list.size() - 1; i >= 0; i--) {
            JSONObject item = list.getJSONObject(i);
            if(commentIds.contains(item.getString("commentId"))){
//                list.remove(i);
                item.put("status", 2);
            };
        }

        BaseRsp rsp=JSONObject.parseObject(jsonRes.toJSONString(), BaseRsp.class);
        return rsp;
    }

    @Override
    public BaseRsp listCommentRecords(Map<String, String> paramMap){
        Map<String, Object> queryMap = structureQueryMap(paramMap);
        if (paramMap.containsKey("postId") && paramMap.get("postId") != null && paramMap.get("postId") != ""){
            queryMap.put("postId", Long.parseLong(paramMap.get("postId")));
        }
        if (paramMap.containsKey("gender") && paramMap.get("gender") != null && paramMap.get("gender") != ""){
            queryMap.put("gender", Integer.valueOf(paramMap.get("gender")));
        }
        if (paramMap.containsKey("status") && paramMap.get("status") != null && paramMap.get("status") != ""){
            queryMap.put("status", Integer.valueOf(paramMap.get("status")));
        }

        // 获取已审核记录列表
        List<CommentAuditDOWithBLOBs> queryList = commentAuditDOMapper.list(queryMap);

        for (int i=0; i<queryList.size(); i++){
            CommentAuditDOWithBLOBs item = queryList.get(i);
            item.setNickname(emojiRecovery(item.getNickname()));
            item.setReplayUserNickname(emojiRecovery(item.getReplayUserNickname()));
            item.setComment(emojiRecovery(item.getComment()));
        }

        // 获取当前获取数据总数
        Integer count = queryList.size();
        System.out.println(MessageFormat.format("[ listCommentRecords ]： total:{0}; content:{1}", count.toString(), queryList.toString()));
        // 获取所有数据总数
        Integer total = commentAuditDOMapper.total(queryMap);

        Integer page = Integer.parseInt(paramMap.getOrDefault("pageNum", "1"));
        Integer limit = Integer.parseInt(paramMap.getOrDefault("pageSize", "100"));

        PageInfoDTO pageInfo = structurePageInfo(queryList, total, count, page, limit);

        return new BaseRsp(pageInfo);
    }

    @Override
    public BaseRsp deleteComment(CommentAuditDOWithBLOBs CommentAuditDOWithBLOBs){
        String url= UrlConstant.ApiServerHost+anchorAdminUrl+"/comments/"+CommentAuditDOWithBLOBs.getUserId()+"/"+CommentAuditDOWithBLOBs.getCommentId();
        String body=HttpInvokeUtil.httpDelete(url,null);
        BaseRsp rsp=JSONObject.parseObject(body,BaseRsp.class);
        return rsp;
    }

    @Override
    public void saveCommentRecord(CommentAuditDOWithBLOBs CommentAuditDOWithBLOBs){
        // 保存已审核数据记录
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("commentId", CommentAuditDOWithBLOBs.getCommentId());
        queryMap.put("status", CommentAuditDOWithBLOBs.getStatus());
        Integer isExist = commentAuditDOMapper.isExist(queryMap);
        if (isExist == 0 ){
            commentAuditDOMapper.insertSelective(CommentAuditDOWithBLOBs);
        }
        else{
            queryMap.put("automatic", CommentAuditDOWithBLOBs.getAutomatic());
            queryMap.put("message", CommentAuditDOWithBLOBs.getMessage());
            commentAuditDOMapper.updateTime(queryMap);
        }
        System.out.println(MessageFormat.format("[ saveCommentRecord ]： {0}", CommentAuditDOWithBLOBs.toString()));
    }

    @Autowired PostAuditDOMapper postAuditDOMapper;
    @Autowired PostImageDOMapper postImageDOMapper;

    @Override
    public BaseRsp postDetail(Map<String, String> paramMap){
        String url= UrlConstant.ApiServerHost + "/dynamic/detail";
        log.info(paramMap.toString());
        String body= HttpInvokeUtil.httpGet(url, paramMap, null);
        JSONObject jsonRes = JSONObject.parseObject(body);
        JSONObject data = (JSONObject) jsonRes.get("data");
        if (data.get("video") != null && data.getJSONObject("video").get("videoId") != null) {
            data.getJSONObject("video").put("videoUrl", aliVodUtils.getMediaUrl(data.getJSONObject("video").getString("videoId"), "mp4"));
        }
        return JSONObject.parseObject(jsonRes.toJSONString(), BaseRsp.class);
    }

    @Override
    public BaseRsp listPosts(Map<String, String> paramMap){
        String url= UrlConstant.ApiServerHost+anchorAdminUrl+"/posts";
        log.info(paramMap.toString());
        String body= HttpInvokeUtil.httpGet(url, paramMap, null);

        Map<String, Object> queryMap = structureQueryMap(paramMap);
        if (paramMap.containsKey("gender") && paramMap.get("gender") != null && paramMap.get("gender") != ""){
            queryMap.put("gender", Integer.valueOf(paramMap.get("gender")));
        }
        if (paramMap.containsKey("status") && paramMap.get("status") != null && paramMap.get("status") != ""){
            queryMap.put("status", Integer.valueOf(paramMap.get("status")));
        }
        Integer limit = Integer.parseInt(queryMap.get("limit").toString()) *  (Integer.parseInt(queryMap.get("offset").toString())+1);
        queryMap.put("limit", limit);
        Set<String> postIds = postAuditDOMapper.listPostId(queryMap);
//        Integer nums = postIds.size();

        JSONObject jsonRes = JSONObject.parseObject(body);
        JSONObject data = (JSONObject) jsonRes.get("data");
//        data.put("total", data.getInteger("total") - nums);
        JSONArray list = (JSONArray) data.get("list");
        for (int i = list.size() - 1; i >= 0; i--) {
            JSONObject item = list.getJSONObject(i);
            if(postIds.contains(item.getString("contentId"))){
//                list.remove(i);
                item.put("status", 2);
            };
            if (item.get("video") != null && item.getJSONObject("video").get("videoId") != null) {
                item.getJSONObject("video").put("videoUrl", aliVodUtils.getMediaUrl(item.getJSONObject("video").getString("videoId"), "mp4"));
            }
        }

        BaseRsp rsp=JSONObject.parseObject(jsonRes.toJSONString(), BaseRsp.class);
        return rsp;
    }

    @Override
    public BaseRsp listPostRecords(Map<String, String> paramMap){
        Map<String, Object> queryMap = structureQueryMap(paramMap);
        if (paramMap.containsKey("gender") && paramMap.get("gender") != null && paramMap.get("gender") != ""){
            queryMap.put("gender", Integer.valueOf(paramMap.get("gender")));
        }
        if (paramMap.containsKey("status") && paramMap.get("status") != null && paramMap.get("status") != ""){
            queryMap.put("status", Integer.valueOf(paramMap.get("status")));
        }

        // 获取已审核记录列表
        List<PostAuditDOWithBLOBs> queryList = postAuditDOMapper.list(queryMap);

        for (int i=0; i<queryList.size(); i++){
            PostAuditDOWithBLOBs item = queryList.get(i);
            item.setNickname(emojiRecovery(item.getNickname()));
            item.setContent(emojiRecovery(item.getContent()));

            List<PostImageDO> imageList = postImageDOMapper.list(item.getContentId());
            if (imageList.size() > 0) {
                item.setImageVos(imageList);
            }
        }

        // 获取当前获取数据总数
        Integer count = queryList.size();
        System.out.println(MessageFormat.format("[ listPostRecords ]： total:{0}; content:{1}", count.toString(), queryList.toString()));
        // 获取所有数据总数
        Integer total = postAuditDOMapper.total(queryMap);

        Integer page = Integer.parseInt(paramMap.getOrDefault("pageNum", "1"));
        Integer limit = Integer.parseInt(paramMap.getOrDefault("pageSize", "100"));

        PageInfoDTO pageInfo = structurePageInfo(queryList, total, count, page, limit);

        return new BaseRsp(pageInfo);
    }

    @Override
    public BaseRsp deletePost(PostAuditDOWithBLOBs postAuditDOWithBLOBs){
        String url= UrlConstant.ApiServerHost+anchorAdminUrl+"/posts/"+postAuditDOWithBLOBs.getUserId()+"/"+postAuditDOWithBLOBs.getContentId();
        String body=HttpInvokeUtil.httpDelete(url,null);
        BaseRsp rsp=JSONObject.parseObject(body,BaseRsp.class);
        return rsp;
    }

    @Override
    public void savePostRecord(PostAuditDOWithBLOBs postAuditDOWithBLOBs){
        // 保存已审核数据记录
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("contentId", postAuditDOWithBLOBs.getContentId());
        queryMap.put("status", postAuditDOWithBLOBs.getStatus());
        if (postAuditDOWithBLOBs.getImageVos()!= null && postAuditDOWithBLOBs.getImageVos().size()>0) {
            postAuditDOWithBLOBs.getImageVos().forEach(img -> {
                img.setPostId(postAuditDOWithBLOBs.getContentId());
                postImageDOMapper.insertSelective(img);
            });
        }
        Integer isExist = postAuditDOMapper.isExist(queryMap);
        if (isExist == 0 ){
            postAuditDOMapper.insertSelective(postAuditDOWithBLOBs);
        }
        else{
            postAuditDOMapper.updateTime(queryMap);
        }
        System.out.println(MessageFormat.format("[ savePostRecord ]： {0}", postAuditDOWithBLOBs.toString()));
    }

    @Autowired FamilyChangeDOMapper familyChangeDOMapper;

    @Override
    public void saveCheckFamily(CheckFamilyDO checkFamilyDO){
        String url= UrlConstant.ApiServerHost+anchorAdminUrl+"/check_family_changedrecord";
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("checkStatus", checkFamilyDO.getCheckStatus());
        paramMap.put("checkType", checkFamilyDO.getCheckType());
        paramMap.put("id", checkFamilyDO.getId());
        paramMap.put("rejectReason", checkFamilyDO.getRejectReason());
        String req = JSONObject.toJSONString(paramMap);
        String body = HttpInvokeUtil.httpPostJson(url, req, UrlConstant.DefaultEncode, null);
        log.info(body);
        familyChangeDOMapper.insert(checkFamilyDO);
    }

    @Override
    public BaseRsp getFamilyList(Map<String, Object> paramMap){
        Object type = paramMap.get("type");
        if(type != null && !type.equals(0)){
            return new BaseRsp(ResultEnum.SUCCESS,
                    ImmutableMap.of("list", familyChangeDOMapper.list(paramMap),
                            "count", familyChangeDOMapper.count(paramMap)
                    ));
        }else {
            String url= UrlConstant.ApiServerHost+anchorAdminUrl+"/query_family_check_apply";
            String body= HttpInvokeUtil.httpGet(url, paramMap);
            JSONObject rep = JSON.parseObject(body);
            JSONObject data = rep.getJSONObject("data");
            return new BaseRsp(ResultEnum.SUCCESS,
                ImmutableMap.of("list", data.getJSONArray("list"),
                        "count", data.getInteger("total")
                ));
        }
    }

    public Map<String, Object>  structureQueryMap(Map<String, String> paramMap){
        Map<String, Object> queryMap = new HashMap<>();
        if (paramMap.containsKey("page") && paramMap.containsKey("limit")){
            queryMap.put("limit", Integer.valueOf(paramMap.get("limit")));
            queryMap.put("offset", (Integer.parseInt(paramMap.get("page")) - 1) * Integer.parseInt(paramMap.get("limit")));
        } else if (paramMap.containsKey("pageNum") && paramMap.containsKey("pageSize")){
            queryMap.put("limit", Integer.valueOf(paramMap.get("pageSize")));
            queryMap.put("offset", (Integer.parseInt(paramMap.get("pageNum")) - 1) * Integer.parseInt(paramMap.get("pageSize")));
        }
        if (paramMap.containsKey("userId") && paramMap.get("userId") != null && paramMap.get("userId") != ""){
            queryMap.put("userId", Integer.valueOf(paramMap.get("userId")));
        }
        if (paramMap.containsKey("gender") && paramMap.get("gender") != null && paramMap.get("gender") != ""){
            queryMap.put("gender", Integer.valueOf(paramMap.get("gender")));
        }
        if (paramMap.containsKey("startTime") && paramMap.containsKey("endTime")){
            queryMap.put("startTime", Long.parseLong(paramMap.get("startTime")));
            queryMap.put("endTime", Long.parseLong(paramMap.get("endTime")));
        }
        System.out.println(queryMap.toString());
        return queryMap;
    }

    public PageInfoDTO structurePageInfo(List list, Integer total, Integer count, Integer page, Integer limit){
        PageInfoDTO pageInfo = new PageInfoDTO();
        pageInfo.setList(list);
        pageInfo.setTotal(total);
        pageInfo.setSize(count);
        pageInfo.setEndRow((page - 1) * limit+count);
        pageInfo.setHasNextPage(count>pageInfo.getEndRow()?true:false);
        pageInfo.setHasPreviousPage(page != 1);
        pageInfo.setIsFirstPage(page == 1);
        pageInfo.setIsLastPage(count>pageInfo.getEndRow()?false:true);
        Integer mor = total>limit?total/limit:0;
        Integer rem = total>limit?total % limit:0;
        pageInfo.setLastPage(rem==0?mor:mor+1);
        pageInfo.setNavigateLastPage(rem==0?mor:mor+1);
        pageInfo.setNextPage(pageInfo.getHasNextPage()?page+1: 0);
        pageInfo.setPageNum(rem==0?mor:mor+1);
        pageInfo.setPageSize(limit);
        pageInfo.setPages(rem==0?mor:mor+1);
        pageInfo.setPrePage(page-1);
        pageInfo.setStartRow((page - 1) * limit+1);
        pageInfo.setStatus(1);  // 用来判断是 已审核数据 还是 未审核数据
        return pageInfo;
    }

}
